package com.fourth.shopping.shrio;

import com.fourth.entity.Administrator;
import com.fourth.entity.Role;
import com.fourth.shopping.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


@Component("myRealm")
public class MyRealm extends AuthorizingRealm {

    @Resource
    LoginService loginService;

    /**
     * 获取授权信息
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //获取用户名
                String username = (String) principals.getPrimaryPrincipal();

        List<Role> role = loginService.getRole(username);


        if (role != null) {

            for (Role role1 : role) {

                info.addRole(role1.getRname());
            }

        }

        return info;
    }

    /**
     * 获取用户登录信息
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        AuthenticationInfo info = null;

        UsernamePasswordToken tk = (UsernamePasswordToken) token;

        String username = tk.getUsername();

        char[] password = tk.getPassword();

        String pass = new String(password);
        Administrator login = loginService.Login(username, pass);
        System.out.println("登录查询是否有该用户：" + login);
        if (login != null && login.getUid() != 0) {
            String name = getName();
            info = new SimpleAuthenticationInfo(username, pass, name);
        }
        return info;
    }
}
